<template>
  <el-dialog :title="$t('productCenter.product.title')" :visible.sync="showState" :before-close="handleClose" :close-on-click-modal="false">
    <el-form ref="formValidate" :model="formValidate" :rules="rules" label-width="150px" class="demo-ruleForm">
      <el-form-item :label="$t('productCenter.product.list.name')" prop="loanProductName">
        <el-input v-model="formValidate.loanProductName" clearable :placeholder="$t('productCenter.product.inputPrompt')" :maxlength="50" />
      </el-form-item>
      <el-form-item :label="$t('productCenter.product.list.type')" prop="loanProductType">
        <el-select v-model="formValidate.loanProductType" :placeholder="$t('common.select')" style="width: 100%" @change="changeLoanProductType">
          <el-option
            v-for="item in $t('productCenter.product.type1')"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="formValidate.loanProductType === 4" :label="$t('productCenter.product.list.method')" prop="calculateType">
        <el-select v-model="formValidate.calculateType" clearable :placeholder="$t('common.select')" style="width: 100%">
          <el-option
            v-for="item in $t('productCenter.product.methods')"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('productCenter.product.list.amount')" prop="loanQuotaMix">
        <el-col :span="5">
          <el-input
            v-model="formValidate.loanQuotaMix"
            :maxlength="50"
            @input="test('loanQuotaMix')"
          />
        </el-col>
        <el-col :span="3" class="tip">
          RP  -
        </el-col>
        <el-col :span="5">
          <el-input
            v-model="formValidate.loanQuotaMax"
            :maxlength="50"
            @input="test('loanQuotaMax')"
          />
        </el-col>
        <el-col :span="3" class="tip">
          RP  {{ $t('productCenter.product.take') }}
        </el-col>
        <el-col :span="5">
          <el-input
            v-model="formValidate.loanQuotaIncrease"
            :maxlength="50"
            @input="test('loanQuotaIncrease')"
          />
        </el-col>
        <el-col :span="3" class="tip">
          {{ $t('productCenter.product.increment') }}
        </el-col>
      </el-form-item>
      <el-form-item prop="loanTermMix">
        <template slot="label">
          <span v-if="formValidate.loanProductType === 3 || formValidate.loanProductType === 4">{{ $t('productCenter.product.list.singlePeriod') }}</span>
          <span v-else>{{ $t('productCenter.product.list.period') }}</span>
        </template>
        <el-col :span="5">
          <el-input
            v-model="formValidate.loanTermMix"
            :maxlength="50"
            @input="test('loanTermMix')"
          />
        </el-col>
        <el-col :span="3" class="tip">
          {{ $t('productCenter.product.day') }}  -
        </el-col>
        <el-col :span="5">
          <el-input
            v-model="formValidate.loanTermMax"
            :maxlength="50"
            @input="test('loanTermMax')"
          />
        </el-col>
        <el-col :span="3" class="tip">
          {{ $t('productCenter.product.day') }}  {{ $t('productCenter.product.take') }}
        </el-col>
        <el-col :span="5">
          <el-input
            v-model="formValidate.loanTermIncrease"
            :maxlength="50"
            @input="test('loanTermIncrease')"
          />
        </el-col>
        <el-col :span="3" class="tip">
          {{ $t('productCenter.product.increment') }}
        </el-col>
      </el-form-item>
      <el-form-item :label="$t('productCenter.product.list.lendRate')" prop="loanDayRate">
        <el-input
          v-model="formValidate.loanDayRate"
          :maxlength="10"
          @input="keyup('loanDayRate')"
        >
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('productCenter.product.list.annualRate')" prop="annualInterestRate">
        <el-input
          v-model="formValidate.annualInterestRate"
          :maxlength="10"
          @input="keyup('annualInterestRate')"
        >
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('productCenter.product.list.technology')" prop="technologyRate">
        <el-input
          v-model="formValidate.technologyRate"
          :maxlength="10"
          @input="keyup('technologyRate')"
        >
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('productCenter.product.list.review')" prop="auditRate">
        <el-input
          v-model="formValidate.auditRate"
          :maxlength="50"
          @input="keyup('auditRate')"
        >
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('productCenter.product.list.gracePeriod')" prop="gracePeriod">
        <el-input
          v-model="formValidate.gracePeriod"
          :maxlength="50"
          @input="test('gracePeriod')"
        >
          <i slot="suffix">{{ $t('productCenter.product.day') }}</i>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('productCenter.product.list.gracePeriodDayRate')" prop="gracePeriodDayRate">
        <el-input
          v-model="formValidate.gracePeriodDayRate"
          :maxlength="50"
          @input="keyup('gracePeriodDayRate')"
        >
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('productCenter.product.list.overdueDayRate')" prop="overdueDayRate">
        <el-input
          v-model="formValidate.overdueDayRate"
          :maxlength="50"
          @input="keyup('overdueDayRate')"
        >
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item v-if="formValidate.loanProductType === 3 || formValidate.loanProductType === 4" :label="$t('productCenter.product.list.periodsNumber')" prop="period">
        <el-select v-model="formValidate.period" :placeholder="$t('common.select')" style="width: 100%" @change="changePeriod">
          <el-option
            v-for="item in periods"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-row v-if="formValidate.loanProductType === 3 || (formValidate.loanProductType === 4 && formValidate.calculateType === 1)" :label="$t('productCenter.product.list.periodsNumber')" prop="period">
        <el-form-item v-for="(item, index) in periodsData" :key="index" :label="$t('productCenter.product.list.overdueDayRate')" :prop="item">
          <template slot="label">
            {{ $t('productCenter.product.list.periodsRate1') }}{{ index + 1 }}{{ $t('productCenter.product.list.periodsRate2') }}
          </template>
          <el-col :span="20">
            <el-input-number
              v-model="formValidate.oughtPayRatio[index]"
              style="width: 100%"
              :step="0.01"
              :precision="2"
              :max="100.00"
              :min="0.01"
              :placeholder="$t('productCenter.product.prompt')"
            />
          </el-col>
          <el-col :span="4" style="padding-left: 10px">%</el-col>
        </el-form-item>
      </el-row>
      <el-form-item :label="$t('productCenter.product.list.state')" prop="status">
        <el-select v-model="formValidate.status" :placeholder="$t('common.select')" style="width: 100%">
          <el-option
            v-for="item in $t('productCenter.product.state')"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">{{ $t('common.operate.cancel') }}</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.operate.sure') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addProduct, updateProduct } from '@/api/product'
import { div } from '@/utils/method'
export default {
  name: 'ProductDialog',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    chooseItem: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      periods: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      periodsData: [],
      submitLoading: false,
      formValidate: {
        id: null,
        loanProductName: null,
        loanProductType: 1,
        calculateType: null,
        loanQuotaMax: 0,
        loanQuotaMix: 0,
        loanQuotaIncrease: 1,
        loanTermMax: 0,
        loanTermMix: 0,
        loanTermIncrease: 1,
        loanDayRate: 0,
        annualInterestRate: 0,
        technologyRate: 0,
        auditRate: 0,
        gracePeriod: 0,
        gracePeriodDayRate: 0,
        overdueDayRate: 0,
        period: 1,
        status: 1,
        oughtPayRatio: []
      },
      rules: this.rulesData()
    }
  },
  computed: {
    showState: {
      get: function() {
        return this.showDialog
      },
      set: function() {
      }
    }
  },
  mounted() {
    this.formValidate = this.chooseItem
  },
  methods: {
    rulesData() {
      const validateLoanQuota = (rule, value, callback) => {
        if (!this.formValidate.loanQuotaMix || !this.formValidate.loanQuotaMax || !this.formValidate.loanQuotaIncrease) {
          callback(new Error(this.$t('productCenter.product.list.amount') + this.$t('common.null')))
        } else {
          const loanQuota = this.formValidate.loanQuotaMax - this.formValidate.loanQuotaMix
          if (loanQuota < 0) {
            callback(new Error(this.$t('productCenter.product.msg.amount')))
          } else if (loanQuota % this.formValidate.loanQuotaIncrease !== 0) {
            callback(new Error(this.$t('productCenter.product.msg.amount')))
          } else {
            callback()
          }
        }
      }
      const validateLoanTerm = (rule, value, callback) => {
        if (!this.formValidate.loanTermMix || !this.formValidate.loanTermMax || !this.formValidate.loanTermIncrease) {
          callback(new Error(this.$t('productCenter.product.list.amount') + this.$t('common.null')))
        } else {
          const loanTerm = this.formValidate.loanTermMax - this.formValidate.loanTermMix
          if (loanTerm < 0) {
            callback(new Error(this.$t('productCenter.product.msg.period')))
          } else if (loanTerm % this.formValidate.loanTermIncrease !== 0) {
            callback(new Error(this.$t('productCenter.product.msg.period')))
          } else {
            callback()
          }
        }
      }
      return {
        loanProductName: [{ required: true, message: this.$t('productCenter.product.list.name') + this.$t('common.null'), trigger: 'blur' }],
        loanProductType: [{ required: true, type: 'number', message: this.$t('productCenter.product.list.type') + this.$t('common.null'), trigger: 'blur' }],
        calculateType: [{ required: true, type: 'number', message: this.$t('productCenter.product.list.method') + this.$t('common.null'), trigger: 'blur' }],
        loanQuotaMix: [{ required: true, validator: validateLoanQuota, trigger: 'blur' }],
        loanTermMix: [{ required: true, validator: validateLoanTerm, trigger: 'blur' }],
        loanDayRate: [{ required: true, message: this.$t('productCenter.product.list.lendRate') + this.$t('common.null'), trigger: 'blur' }],
        annualInterestRate: [{ required: true, message: this.$t('productCenter.product.list.annualRate') + this.$t('common.null'), trigger: 'blur' }],
        technologyRate: [{ required: true, message: this.$t('productCenter.product.list.technology') + this.$t('common.null'), trigger: 'blur' }],
        auditRate: [{ required: true, message: this.$t('productCenter.product.list.review') + this.$t('common.null'), trigger: 'blur' }],
        gracePeriod: [{ required: true, message: this.$t('productCenter.product.list.gracePeriod') + this.$t('common.null'), trigger: 'blur' }],
        gracePeriodDayRate: [{ required: true, message: this.$t('productCenter.product.list.gracePeriodDayRate') + this.$t('common.null'), trigger: 'blur' }],
        overdueDayRate: [{ required: true, message: this.$t('productCenter.product.list.overdueDayRate') + this.$t('common.null'), trigger: 'blur' }],
        period: [{ required: true, type: 'number', message: this.$t('productCenter.product.list.periodsNumber') + this.$t('common.null'), trigger: 'blur' }],
        status: [{ required: true, type: 'number', message: this.$t('productCenter.product.list.state') + this.$t('common.null'), trigger: 'blur' }],
        oughtPayRatio: [{ required: true, message: this.$t('productCenter.product.list.automaticSettlementRatio') + this.$t('common.null'), trigger: 'blur' }]
      }
    },
    handleClose() {
      this.$emit('change-dialog', 'editDialog', false)
      this.$refs['formValidate'].clearValidate()
    },
    fromData() {
      const value = this.formValidate
      const data = {
        id: value.id,
        loanProductName: value.loanProductName,
        loanProductType: value.loanProductType,
        loanQuotaMax: value.loanQuotaMax,
        loanQuotaMix: value.loanQuotaMix,
        loanQuotaIncrease: value.loanQuotaIncrease,
        loanTermMax: value.loanTermMax,
        loanTermMix: value.loanTermMix,
        loanTermIncrease: value.loanTermIncrease,
        gracePeriod: value.gracePeriod,
        period: value.period,
        status: value.status
      }
      if (value.loanProductType === 3) {
        data['calculateType'] = 1
      } else if (value.loanProductType === 1 || value.loanProductType === 2) {
        data['calculateType'] = null
      } else {
        data['calculateType'] = value.calculateType
      }
      data.loanDayRate = div(value.loanDayRate, 100)
      data.annualInterestRate = div(value.annualInterestRate, 100)
      data.technologyRate = div(value.technologyRate, 100)
      data.auditRate = div(value.auditRate, 100)
      data.gracePeriodDayRate = div(value.gracePeriodDayRate, 100)
      data.overdueDayRate = div(value.overdueDayRate, 100)
      if (value.loanProductType === 3 || (value.loanProductType === 4 && value.calculateType === 1)) {
        const oughtPayRatio = value.oughtPayRatio
        if (oughtPayRatio && oughtPayRatio.length > 0) {
          let num = 0
          const numData = []
          oughtPayRatio.forEach(v => {
            const i = div(v, 100)
            num += i
            numData.push(i)
          })
          if (num !== 1) {
            this.submitLoading = false
            this.msg.error(this.$t('productCenter.product.msg.oughtPayRatio'))
            return
          }
          data['oughtPayRatio'] = numData
        }
      }
      return data
    },
    handleSubmit() {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const data = this.fromData()
          if (data.id) {
            updateProduct(data)
              .then(res => {
                this.submitLoading = false
                if (res.success) {
                  this.$message.success(this.$t('common.tip.editSuccess'))
                  this.$emit('change-dialog', 'editDialog', false)
                  this.$emit('edit-success')
                  this.handleClose()
                } else {
                  this.$message.error(res.message)
                }
              })
              .catch(err => {
                this.$message.error(err.message)
                this.submitLoading = false
              })
          } else {
            addProduct(data)
              .then(res => {
                this.submitLoading = false
                if (res.success) {
                  this.$message.success(this.$t('common.tip.addSuccess'))
                  this.$emit('change-dialog', 'editDialog', false)
                  this.$emit('edit-success')
                  this.handleClose()
                } else {
                  this.$message.error(res.message)
                }
              })
              .catch(err => {
                this.$message.error(err.message)
                this.submitLoading = false
              })
          }
        }
      })
    },
    test(data) {
      let value = this.formValidate[data]
      if (value.length > 0) {
        value = value.replace(/[^0-9]/g, '')
      }
      this.formValidate[data] = value
    },
    keyup(data) {
      let value = this.formValidate[data]
      value = value.replace(/[^\d.]/g, '') // 清除"数字"和"."以外的字符
      value = value.replace(/^\./g, '') // 验证第一个字符是数字
      value = value.replace(/\.{2,}/g, '.') // 只保留第一个, 清除多余的
      value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
      const num = value.indexOf('.')
      if (num < 0 && value !== '') { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        value = parseFloat(value)
      }
      if (num > -1) { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        let before = value.substring(0, num)
        const after = value.substring(num)
        if (before !== '0') {
          before = parseFloat(before)
          value = before + '' + after
        }
      }
      this.formValidate[data] = value
    },
    changePeriod(data) {
      if (data > 1 && (this.formValidate.loanProductType === 3 || (this.formValidate.loanProductType === 4 && this.formValidate.calculateType === 1))) {
        this.rules = this.rulesData()
        this.periodsData = []
        for (let i = 0; i < data; i++) {
          const str = 'periods' + i
          const validatePeriod = (rule, value, callback) => {
            if (!this.formValidate.oughtPayRatio[i]) {
              callback(new Error(this.$t('productCenter.product.list.periodsRate1') + (i + 1) + this.$t('productCenter.product.list.periodsRate2') + this.$t('common.null')))
            } else {
              callback()
            }
          }
          this.periodsData.push(str)
          this.rules[str] = [{ required: true, validator: validatePeriod, trigger: 'blur' }]
        }
        const length = this.formValidate.oughtPayRatio.length
        if (length > data) {
          this.formValidate.oughtPayRatio.splice(0, data)
        } else if (length < data) {
          for (let i = 0; i < data - length; i++) {
            this.formValidate.oughtPayRatio.push(0.01)
          }
        }
      }
    },
    changeLoanProductType(data) {
      if (data === 1 || data === 2) {
        this.formValidate.period = 1
        this.changePeriod(1)
      } else {
        this.formValidate.period = null
        this.changePeriod(null)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
p{
  text-align: center;
}
.tip{
  background-color: #f2f2f2;
  text-align: center;
}
</style>
